import { cryptStr } from '@/utils/rsa'
import Message from '@arco-design/web-vue/es/message'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  method: 'POST',
  timeout: 60 * 1000, //超时时间 一分钟
  headers: { 'Content-Type': 'application/json' },
  // 跨域请求时发送Cookie
  withCredentials: true,
})
//请求拦截器
request.interceptors.request.use(function (config: any) {
  // 加密数据 (正式环境)
  const route_name = localStorage.getItem('route_name') || ''
  config.headers['X-Header-Web-Url'] = route_name

  if (import.meta.env.MODE == 'production') {
    config.headers['X-Header-Rsa-V'] = 1
    config.data = {
      _body: cryptStr(JSON.stringify(config.data)),
      ...config.data,
    }
  }

  const token = localStorage.getItem('token')

  // 生产版本 控制
  const XRequestIP: any = localStorage.getItem('X-Request-IP')
  // 正常header
  const headers = {
    Authorization: token || '',
  }
  // 区别生产版本
  const headersIP = {
    Authorization: token || '',
    'X-Request-IP': XRequestIP,
  }
  Object.assign(config.headers, XRequestIP ? headersIP : headers)

  return config
})
// 响应拦截器
request.interceptors.response.use(
  async function (response) {
    const code = response.data.code
    const message = response.data.message

    if (code == 302 || code == 401 || code == 305) {
      // 捕捉错误 仅执行一次
      if ((window as any).isTokenLapse) return
      ;(window as any).isTokenLapse = true
      Message.error(message)
      router.push({ name: 'login' })
      return Promise.reject(response)
    } else if (code == 303) {
      Message.error(message)
      router.push({ name: 'login' })
      return Promise.reject(response)
    } else if (code == 304) {
      Message.error(message)
      return Promise.reject(response)
    } else if (code != 200) {
      Message.error(message)
      return Promise.reject(response)
    }
    return Promise.resolve(response.data)
  },
  //接受错误信息
  function (error) {
    if (error.Message.includes('timeout')) {
      Message.error('网络连接超时，请刷新页面重试！')
      return Promise.reject(error)
    }
    Message.error('网络错误')
    return Promise.reject(error)
  }
)

export default request
